package integracion;

import java.util.ArrayList;

import javax.naming.NamingException;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import logs.LogRankingDTO;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import delegate.BusinessDelegate;
import dtos.ArticuloDTO;

@Path("/bestSeller")
public class RankingRS {

	@POST
	@Path("/procesar")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public String informarMasVendidos(String json) {
		Gson gson = new Gson();
		LogRankingDTO logRanking = new LogRankingDTO();
	    JsonParser parser = new JsonParser();
	    
	    JsonObject jsObj = parser.parse(json).getAsJsonObject();
	    
	    JsonArray jsArray =  jsObj.getAsJsonArray("rankings");

	    ArrayList<ArticuloDTO> articulosDTO= new ArrayList<ArticuloDTO>();

	    for(JsonElement obj : jsArray )
	    {
	    	ArticuloDTO art = gson.fromJson( obj , ArticuloDTO.class);
	    	articulosDTO.add(art);
	    }
	    
	    logRanking.setEstado("OK");
		try {
			BusinessDelegate.getInstancia().registrarRanking(articulosDTO);
		} catch ( NamingException e) {
			logRanking.setEstado("ERROR");
			logRanking.setMensaje(e.getMessage());
			e.printStackTrace();
		}
		String logRankingJSON = gson.toJson(logRanking);
		System.out.println(logRankingJSON);
		return logRankingJSON;
	}
}
